package com.lance.answer.question_import;

import com.lance.answer.dto.Item;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.Constant;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.List;

/**
 * @author yixun
 * @version 2.0.0
 * @description
 * @date 2021-05-28 22:22
 * @since 2.0.0
 */
public class AdminBasicTest2AndSave {

        //管理学基础 2065001457555 19940419
        public static void main(String[] args) throws Exception {
            String subjectCode = "基础会计";
            ChromeDriver driver = Util.getDriver(null);
            String url = "http://student.ouchn.cn/";
            driver.get(url);
            Thread.sleep(2000);
            //  login(driver, "2065001457555", "19940419");
            Util.login(driver, "2065001457729", "20000519");
            //   login(driver, "2065001457555", "19940419");

//        WebDriver driver = Util.getDriver();
//        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
//        driver.get(url);
//        Thread.sleep(3000L);
//        Util.login(driver, userName, password);


            Util.switchToFirst(driver);
            Thread.sleep(2000);
            // 形考作业的链接
            // 形考作业的链接 经济数学基础
            System.err.println("???????????????????");
            Util.clickCourseTaskUrl(driver, Constant.SUBJECT.get(subjectCode));
            List<String> urlTasks = Util.getCourseTaskUrl(subjectCode);
            Util.switchToLast(driver);
            for (String urlTask : urlTasks) {
                Thread.sleep(2 * 1000);
                driver.get(urlTask);
                // 过滤资源文件下载
                if (urlTask.contains("resource")) {
                    continue;
                }
                // 过滤平时行为表现 （如：管理心理学）
                if (urlTask.contains("mod/assign")) {
                    continue;
                }
                System.err.println("urlTask:" + urlTask);
                String taskId = urlTask.substring(urlTask.indexOf("id=") + 3);
                // box py-3 quizattempt 找到答题区域 点击开始答题
                try {
                    WebElement doWorkArea = driver.findElement(By.cssSelector("div[class='box py-3 quizattempt']"));
                    doWorkArea.findElement(By.cssSelector("button[class='btn btn-secondary']")).click();
                } catch (Exception e) {
                    System.err.println("taskUrl:" + urlTask + "  occur error");
                    //  e.printStackTrace();
                    // FIXME 这里当发现异常时：说明该taskUrl不是做作业的链接url，就需要跳过当前URL。
                    continue;
                }

                // 这个url也有一定的信息
                Util.goHomePageIndex(driver);

                // FIXME 当前试卷页面这里可能不在首页（第一页），需要回到首页，按顺序做题
                //  http://xinjiang.ouchn.cn/mod/quiz/attempt.php?attempt=283948&page=2&cmid=166319
                // submitbtns
                Thread.sleep(2000);

                boolean hashNextPage = true;
                // 单选
                List<Question> singleChoiceQuestions = Lists.newArrayList();
                // 多选
                List<Question> multiChoiceQuestions = Lists.newArrayList();
                // 判断题
                List<Question> trueFalseQuestions = Lists.newArrayList();
                // 填空题
                List<Question> textQuestions = Lists.newArrayList();

                // 简答题
                List<Question> simpleQuestions = Lists.newArrayList();
                while (hashNextPage) {
                    try {
                        // 防止太快
                        Thread.sleep(2 * 1000);
                        for (WebElement singleSubject : Util.getSinglePageQuestionList(driver)) {

                            if(null == singleSubject){
                                continue;
                            }
                            String answerClass = singleSubject.getAttribute("class");
                            // informationitem  description description
                            if(Strings.isNullOrEmpty(answerClass)){
                                continue;
                            }
                            if(answerClass.contains("description")||answerClass.contains("informationitem")){
                                continue;
                            }

                            Question question = new Question();
                            question.setAnalyze("无");
                            question.setDifficult(1);
                            question.setGradeLevel(21);
                            question.setSubjectId(18);

                            String questionId = singleSubject.getAttribute("id");
                            // 这里的questionId是题目的ID
                            System.err.println("questionId:" + questionId);
                            WebElement contentElement = singleSubject.findElement(By.className("content"));

                            WebElement hiddenElement = singleSubject.
                                    findElement(By.cssSelector("input[type='hidden']"));
                            // 题干
                            String name = hiddenElement.getAttribute("name");
                            System.err.println("name:" + name);
                            // qtext
                            // 题目标题
                            String title = Util.getTitle(contentElement);
                            question.setTitle(title);

                            System.err.println("qTitleElement:" + title);
                            // 题目提示 tip prompt
                            WebElement promptElement = Util.findByClassName(contentElement, "prompt");
                            if (null != promptElement) {
                                System.err.println("promptElement:" + promptElement.getText());
                            }

                            // FIXME 填空题没有answer  好像整个填空题都有问题，只能填一个答案，但是有的问题有两个空。
                            // FIXME 填空题没有answer
                            //      WebElement answerElement = contentElement.findElement(By.className("answer"));
                            WebElement answerElement = Util.findByClassName(contentElement, "answer");
                            String labelType = "";
                            List<Item> items = Lists.newArrayList();
                            question.setItems(items);
                            if (null != answerElement) {
                                // 找到每一个选项
                                // 针对多选和单选和判断题
                                for (WebElement singleAnswerElement : answerElement.
                                        findElements(By.cssSelector("div[class='r0'],div[class='r1']"))) {
                                    // 答案的序号 判断题没有序号 多选和单选有序号
                                    String answerNumber = "";
                                    WebElement numberElement = Util.findByClassName(singleAnswerElement, "answernumber");
                                    if (numberElement != null) {
                                        answerNumber = numberElement.getText();
                                    }
                                    // 每个答案的文本 p标签 =单选和多选 label标签=判断题
                                    // fixme 5-28有的答案是纯图片。
                                    //     String answerContent = singleAnswerElement.findElement(By.cssSelector("p,label")).getText();
//                                String answerContent = singleAnswerElement.findElement(
//                                        By.cssSelector("div[class='flex-fill ml-1']")).getText();
                                    String answerContent = Util.getAnswer(singleAnswerElement);
                                    // 找到单选框或复选框
                                    WebElement checkboxElement = singleAnswerElement.
                                            findElement(By.cssSelector("input[type='checkbox'],input[type='radio']"));
                                    labelType = checkboxElement.getAttribute("type");
                                    // 这里的ID是每个选项的ID
                                    // answerContent是每个选项的内容
                                    String id = checkboxElement.getAttribute("id");
                                    System.out.println("id:" + id);
                                    System.out.println("answer:" + answerNumber + answerContent);
                                    //   System.err.println(id + "\t" + answerNumber + "\t" + answerContent);
                                    Item item = new Item();
                                    item.setPrefix(answerNumber);
                                    item.setContent(answerContent);
                                    if (Strings.isNullOrEmpty(answerContent)) {
                                        item.setPrefix(answerContent);
                                    }
                                    items.add(item);
                                }
                            }

                            answerClass = singleSubject.getAttribute("class");
                            // 简单题que essay manualgraded notyetanswered
                            if (answerClass.contains("essay")) {
                                WebElement iframe = Util.findByTagName(answerElement, "iframe");
                                // 等于选项的ID
                                question.setQuestionType(5);
                                question.setCorrect("简单题");
                                simpleQuestions.add(question);
                            }
                            // 判断题 que truefalse manualgraded notyetanswered  que truefalse deferredfeedback notyetanswered
                            if (answerClass.contains("truefalse")) {
                                question.setQuestionType(3);
                                question.setCorrect("对");
                                trueFalseQuestions.add(question);
                            }
                            // 填空题 que shortanswer deferredfeedback notyetanswered
                            if (answerClass.contains("shortanswer")) {
                                WebElement textElement = contentElement.findElement(By.cssSelector("input[type='text']"));
                                String id = textElement.getAttribute("id");
                                // 等于选项的ID
                                question.setQuestionType(4);
                                question.setCorrect("填空题");
                                textQuestions.add(question);
                            }
                            // 多选|单选：que multichoice deferredfeedback notyetanswered
                            if (answerClass.contains("multichoice")) {
                                if ("radio".equals(labelType)) {
                                    question.setQuestionType(1);
                                    singleChoiceQuestions.add(question);
                                }
                                if ("checkbox".equals(labelType)) {
                                    question.setCorrectArray(new String[]{"A", "B"});
                                    question.setQuestionType(2);
                                    multiChoiceQuestions.add(question);
                                }
                            }
                        }

                        // FIX ME 获取当前页面的下一页信息 设置为while还是有下一页就继续循环
                        WebElement nextPage = Util.findNextPage(driver);
                        if (nextPage != null) {
                            nextPage.click();
                        } else {
                            hashNextPage = false;
                        }

                    } catch (Exception e) {
                        System.err.println("出错啦！！！！" + urlTask);

                        e.printStackTrace();
                        Thread.sleep(2000);
                    }

                    Thread.sleep(2000);
                }
                // 输出JSON文件；  {id}-题型.json
                String rootPath = "/Users/guiliangzhou/IdeaProjects/answer-tool/src/main/resources/00975/question/";
                Util.fileWriteList(rootPath + taskId + "-1-1-单选题.json", singleChoiceQuestions);
                Util.fileWriteList(rootPath + taskId + "-2-2-多选题.json", multiChoiceQuestions);
                Util.fileWriteList(rootPath + taskId + "-3-3-判断题.json", trueFalseQuestions);
                Util.fileWriteList(rootPath + taskId + "-4-5-简答题.json", simpleQuestions);
                Util.fileWriteList(rootPath + taskId + "-4-4-填空题.json", textQuestions);


                Thread.sleep(2000);
                //    break;
            }

            Thread.sleep(500000);
            driver.quit();
        }


    }
